<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/
	protected $layout = 'layouts.application';
    public function __construct(User $user, Category $category, Product $product, Contact $contact) {
        parent::__construct();
        $this->user = $user;
        $this->category = $category;
        $this->product = $product;
        $this->contact = $contact;
    }

	public function showWelcome() {
		$view = View::make('home.index')->with(array(
        ));
		$this->layout->content = $view;
	}
	
	public function showCategory() {
		$products = $this->product->getAllProductsPublish();
		$view = View::make('home.category')->with(array(
			'products' => $products,
        ));
		$this->layout->content = $view;
	}

    /**
     * show page login (admin)
     * @author Thuan Truong
     */
    public function adminLogin() {
        $is_login = BaseController::isLogin();
        $this->layout = View::make('layouts.admin_login');
        $view = View::make('home.admin_login')->with(array(
        ));
        
        $this->layout->content = $view;
    }
    
    /**
     * show admin panel 
     * @author Thuan Truong
     */
    public function adminPanel() {
        $is_login = BaseController::isLogin();
        $this->layout = View::make('layouts.admin_panel');
        
        $num_users = $this->user->countAllUser();
        $num_categories = $this->category->countAllCategory();
        $num_products = $this->product->countAllProducts();
        $num_contact = $this->contact->countAllContacts();
         
        $view = View::make('home.dashboard')->with(array(
            'num_users' => $num_users,
            'num_categories' => $num_categories,
            'num_products' => $num_products,
            'num_contacts' => $num_contact,
        ));
        
        $this->layout->content = $view;
    }
	
	/**
	 * Upload image for CKeditor
	 * @author Duc Nguyen
	 */
	public function ckeditorImage() {
		$result = array();
		$file = Input::file('upload');
		$mime = strstr($file->getClientMimeType(), '/', true);
		if($mime == 'image') {
			$path = 'uploads/ckeditor';
			$random  = md5(uniqid());
			$extension  = $file->getClientOriginalExtension();
			$filename   = $random.'.'.$extension;
			if($file->move(public_path(). '/'. $path, $filename)) {
				$url = url($path. '/'. $filename);
			} else {
				$result['error'] = 'Unable to insert image.';
			}
		} else {
			$result['error'] = 'This is not an image.';
		}
		$funcNum = Input::get('CKEditorFuncNum') ;
		$message = '';
		echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
	}
	
	/**
	 * Delete media
	 * @author Duc Nguyen 
	 */
	public function deleteMedia($id) {
		$result = array(
			'status' => 1,
		);
		$media = $this->media->find($id);
		$media->is_deleted = 1;
		$media->save();
		return Response::json($result);
	}
	
	/**
	 * Upload Image
	 * Use Jquery File Uploader
	 * 
	 * http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
	 * 
	 * @author Duc Nguyen
	 */
	public function upload() {
		$result = array(
			'status' => 'error'
		);
		$current_time = date('YmdHis');
		// A list of permitted file extensions
		$allowed_image = array('png', 'jpg', 'gif', 'jpeg');
		$allowed_file = array('zip', 'doc', 'docx', 'pdf', 'txt', 'csv', 'pptx', 'mpp', 'xlsx', 'png', 'jpg', 'gif');
		
		$extension_image = array('png', 'jpg', 'gif', 'jpeg');
		
		if(empty($_FILES)) {
		    $result['message'] = 'Please upload file less than 3Mb';
		}
		
		if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) {
			$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
			$name_file = explode('.', $_FILES['upl']['name']);
			$name_file = $name_file[0];
            $name_file_origin = $name_file;
            
            $name_file = uniqid(rand(), true);
            
			$file_size = $_FILES['upl']['size']; 
			
			$check_validate = true;
			$format_upl = Input::get('format_upl', '');
			if ($format_upl == 'image' && !in_array(strtolower($extension), $allowed_image)) {
				$result['message'] = 'Định dạng ảnh không đúng.';
				$check_validate = false;
			}
			if ($format_upl == 'file' && !in_array(strtolower($extension), $allowed_file)) {
				$result['message'] = 'Định dạng file không đúng.';
				$check_validate = false;
			}
			if ($format_upl != 'file' && $format_upl != 'image') {
				$check_validate = false;
			}
			if (!$check_validate) {
				return Response::json($result);
			}
			
			// Initial media
			$media = new Media();
			$media->name = $name_file;
			$media->extension = $extension;
			$media->file_size = $file_size;
			
			if (in_array(strtolower($extension), $extension_image)) {
				$media->type = 1;
			} else {
				$media->type = 3;
			}
			
			$check_validate = false;	
			if (in_array(strtolower($extension), $allowed_image)) {
				/*
				 * If image then generate thumbnail, medium image
				* thumbnail: 200x200
				* medium: 640x640
				* original: 1200x1200
				*/
				$new_path = public_path().'/uploads/images/original/'.$name_file.'_'.$current_time.'.'.$extension;
				if(move_uploaded_file($_FILES['upl']['tmp_name'], $new_path)) {
					
					// Thumbnail
					$thumnail = public_path().'/uploads/images/thumb/'.$name_file.'_'.$current_time.'.'.$extension;
					$this->smart_resize_image($new_path , null, 200, 200, true , $thumnail , false , false , 100);
					
					// Medium
					$medium = public_path().'/uploads/images/medium/'.$name_file.'_'.$current_time.'.'.$extension;
					$this->smart_resize_image($new_path , null, 640, 640, true , $medium , false , false , 100);
					
					// Resize original
					$original = public_path().'/uploads/images/original/'.$name_file.'_'.$current_time.'.'.$extension;
					$this->smart_resize_image($new_path , null, 1200, 1200, true , $original , false , false , 100);
					
					$media->path = '/uploads/images';
					$media->thumb = '/thumb/'.$name_file.'_'.$current_time.'.'.$extension;
					$media->medium = '/medium/'.$name_file.'_'.$current_time.'.'.$extension;
					$media->original = '/original/'.$name_file.'_'.$current_time.'.'.$extension;
					
					$check_validate = true;
				}
				
			}
			
			if (in_array(strtolower($extension), $allowed_file)) {
				$new_path = public_path().'/uploads/files/'.$name_file.'_'.$current_time.'.'.$extension;
				if (move_uploaded_file($_FILES['upl']['tmp_name'], $new_path)) {
					$media->path = '/uploads/files';
					$media->original = "/".$name_file.'_'.$current_time.'.'.$extension;
					$check_validate = true;
				}
			}
			if ($check_validate) {
				$media->save();
				
				$result['status'] = 'success';
				$result['media'] = array(
					'id' => $media->id,
					'name_file' => $name_file_origin,
					'extension' => $extension,
					'thumb' => $media->path.$media->thumb,
					'original' => $media->path.$media->original,
					'caption' => $media->caption ? $media->caption : '',
					'deleteUrl' => URL::to('/media/delete/'.$media->id),
					'is_image' => $media->type == 1 ? 1 : 0,
				);
			}
			
		}
		
		return Response::json($result);
	}
	
	
	/**
	 * Easy image resize function
	* @param  $file - file name to resize
	* @param  $string - The image data, as a string
	* @param  $width - new image width
	* @param  $height - new image height
	* @param  $proportional - keep image proportional, default is no
	* @param  $output - name of the new file (include path if needed)
	* @param  $delete_original - if true the original image will be deleted
	* @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
	* @param  $quality - enter 1-100 (100 is best quality) default is 100
	* @return boolean|resource
	* @author Duc Nguyen
	*/
	function smart_resize_image($file,
			$string             = null,
			$width              = 0,
			$height             = 0,
			$proportional       = false,
			$output             = 'file',
			$delete_original    = true,
			$use_linux_commands = false,
			$quality = 100
	) {
	
		if ( $height <= 0 && $width <= 0 ) return false;
		if ( $file === null && $string === null ) return false;
	
		# Setting defaults and meta
		$info                         = $file !== null ? getimagesize($file) : getimagesizefromstring($string);
		$image                        = '';
		$final_width                  = 0;
		$final_height                 = 0;
		list($width_old, $height_old) = $info;
		$cropHeight = $cropWidth = 0;
	
		# Calculating proportionality
		if ($proportional) {
			/*if      ($width  == 0)  $factor = $height/$height_old;
			elseif  ($height == 0)  $factor = $width/$width_old;
			else                    $factor = min( $width / $width_old, $height / $height_old );
	
			$final_width  = round( $width_old * $factor );
			$final_height = round( $height_old * $factor );
			*/
			if ($width_old <= $width && $height_old <= $height) {
				$final_width = $width_old;
				$final_height = $height_old;
			}
			if ($width_old <= $width && $height_old > $height) {
				$final_height = $height;
				$final_width = round( ($height / $height_old) * $width_old);
			}
			if ($width_old > $width && $height_old <= $height) {
				$final_width = $width;
				$final_height = round( ($width / $width_old) * $height_old);
			}
			if ($width_old > $width && $height_old > $height) {
				$factor = min( $width / $width_old, $height / $height_old );
				$final_width  = round( $width_old * $factor );
				$final_height = round( $height_old * $factor );
			}
			
		}
		else {
			$final_width = ( $width <= 0 ) ? $width_old : $width;
			$final_height = ( $height <= 0 ) ? $height_old : $height;
			$widthX = $width_old / $width;
			$heightX = $height_old / $height;
			 
			$x = min($widthX, $heightX);
			$cropWidth = ($width_old - $width * $x) / 2;
			$cropHeight = ($height_old - $height * $x) / 2;
		}
	
		# Loading image to memory according to type
		switch ( $info[2] ) {
		case IMAGETYPE_JPEG:  $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string);  break;
		case IMAGETYPE_GIF:   $file !== null ? $image = imagecreatefromgif($file)  : $image = imagecreatefromstring($string);  break;
		case IMAGETYPE_PNG:   $file !== null ? $image = imagecreatefrompng($file)  : $image = imagecreatefromstring($string);  break;
		default: return false;
		}
	
	
		# This is the resizing/resampling/transparency-preserving magic
		$image_resized = imagecreatetruecolor( $final_width, $final_height );
		if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
		$transparency = imagecolortransparent($image);
		$palletsize = imagecolorstotal($image);
	
		if ($transparency >= 0 && $transparency < $palletsize) {
		$transparent_color  = imagecolorsforindex($image, $transparency);
		$transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
		imagefill($image_resized, 0, 0, $transparency);
		imagecolortransparent($image_resized, $transparency);
		}
		elseif ($info[2] == IMAGETYPE_PNG) {
		imagealphablending($image_resized, false);
		$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
		imagefill($image_resized, 0, 0, $color);
		imagesavealpha($image_resized, true);
		}
		}
		imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
	
	
		# Taking care of original, if needed
		if ( $delete_original ) {
			if ( $use_linux_commands ) exec('rm '.$file);
			else @unlink($file);
		}
	
		# Preparing a method of providing result
		switch ( strtolower($output) ) {
		case 'browser':
		$mime = image_type_to_mime_type($info[2]);
		header("Content-type: $mime");
		$output = NULL;
		break;
		case 'file':
			$output = $file;
			break;
			case 'return':
			return $image_resized;
			break;
			default:
			break;
		}
	
		# Writing image according to type to the output destination and image quality
		switch ( $info[2] ) {
		case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
		case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
		case IMAGETYPE_PNG:
		$quality = 9 - (int)((0.9*$quality)/10.0);
			imagepng($image_resized, $output, $quality);
			break;
			default: return false;
		}
	
		return true;
	}
	
	/**
	 * Update caption image
	 * @param $id ID of image
	 * @param $caption: text
	 * @author Duc Nguyen
	 * @return JSON
	 */
	public function editCaption() {
		$result = array(
			'status' => 0,
			'message' => Lang::get('reminders.error_action')
		);
		$id = Input::get('id', 0);
		$image = $this->media->whereRaw('id = ? and type = ? and is_deleted = ?', array($id, 1, 0))->first();
		if (count($image) > 0) {
			$caption = Input::get('caption', '');
			$image->caption = $caption;
			$image->save();
			
			$result['status'] = 1;
			$result['image'] = array(
								'id' => $image->id,
								'caption' => $image->caption
							);
			$result['message'] = Lang::get('nav.page.uploader.update_caption');
		}
		return Response::json($result);
	}
	
	/**
	 * Change language
	 * @param $language_id
	 * @author Duc Nguyen
	 */
	public function changeLanguage() {
		$language_code = Input::get('select_language');
		
		if ($language_code == 'EN') {
			Session::put('language_id', 1);
			Session::put('language_code', 'en');
			return Redirect::to('/en');
		} else {
			Session::put('language_id', 2);
			Session::put('language_code', 'vi');
			return Redirect::to('/vi');
		}
	}
}
